package com.xpjhs.shiro;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.xpjhs.role.model.Role;
import com.xpjhs.user.dao.UserDao;
import com.xpjhs.user.model.User;

public class ShiroRealm extends AuthorizingRealm {

	private UserDao userDao;

	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		// 根据用户配置用户与权限
		if (principals == null) {
			throw new AuthorizationException(
					"PrincipalCollection method argument cannot be null.");
		}
		String name = (String) getAvailablePrincipal(principals);
		List<String> roles = new ArrayList<String>();
		List<Role> roleList = new ArrayList<Role>();
		/*User user = userDao.findUserByUsername(name);
		Role role = new Role();
		role.setRoleName("member");
		roleList.add(role);
		user.setRoles(roleList);
		if (user.getUsername().equals(name)) {
			for (Role role2 : user.getRoles()) {
				roles.add(role2.getRoleName());
			}
		} else {
			throw new AuthorizationException();
		}
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		// 增加角色
		info.addRoles(roles);
		return info;*/
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		User user = userDao.findUserByUsername(token.getUsername());
		SimpleAuthenticationInfo info = null;
		if (user.getUsername().equals(token.getUsername())) {
			info = new SimpleAuthenticationInfo(user.getUsername(),
					user.getPassword(), getName());
		}
		return info;
	}

}
